<template>
  <div class="scrollText" ref="outer">
    <div
      class="st-inner text-left"
      :class="{ 'st-scrolling': state.needToScroll }"
    >
      <span class="st-section" ref="inner">{{ text }}</span>
      <!-- <span class="st-section" v-if="state.needToScroll">{{ text }}</span> -->
      <!-- 加两条是为了滚动的时候实现无缝衔接 -->
    </div>
  </div>
</template>
<script>
import { onMounted, nextTick, onBeforeUnmount, reactive, ref } from "vue";
export default {
  name: "MarqeeCountry",
  props: { text: String },
  setup(props) {
    const state = reactive({
      needToScroll: false,
      text: "",
      _checkTimer: null
    });
    onMounted(() => {
      check();
      // startCheck();
    });
    onBeforeUnmount(() => {
      // stopCheck();
    });
    // 检查当前元素是否需要滚动
    const check = () => {
      setText();
      nextTick(() => {
        let flag = isOverflow();
        state.needToScroll = flag;
      });
    };
    const outer = ref(null);
    const inner = ref(null);
    // 判断子元素宽度是否大于父元素宽度，超出则需要滚动，否则不滚动
    const isOverflow = () => {
      let outerval = outer.value;
      let innerval = inner.value;
      let outerWidth = getWidth(outerval);
      let innerWidth = getWidth(innerval);
      return innerWidth > outerWidth;
    };

    // 获取元素宽度
    const getWidth = el => {
      let { width } = el.getBoundingClientRect();
      return width;
    };

    // 获取到父组件传过来的内容复传给this.text
    const setText = () => {
      state.text = props.text || "";
    };

    // 增加定时器，隔一秒check一次
    const startCheck = () => {
      state._checkTimer = setInterval(check, 1000);
      check();
    };

    // 关闭定时器
    const stopCheck = () => {
      clearInterval(state._checkTimer);
    };
    return {
      state,
      outer,
      inner,
      check,
      stopCheck,
      startCheck,
      setText,
      getWidth,
      isOverflow
    };
  }
};
</script>
<style lang="less" scoped>
.scrollText {
  overflow: hidden;
  white-space: nowrap;
}
.st-inner {
  // overflow: hidden;
  width: 100%;
}
.st-scrolling .st-section {
  padding: 0 5px;
  display: inline-block;
  width: 100%;
}

// 向左匀速滚动动画
.st-scrolling {
  animation: scroll 10s linear infinite;
}

@keyframes scroll {
  0% {
    transform: translate3d(0%, 0, 0);
  }
  100% {
    transform: translate3d(-50%, 0, 0);
  }
}
</style>
